import axios from 'axios'
import {Message} from 'element-ui'
import store from '@/store'

import {removeToken} from '@/utils/token'

import router from '@/router/index'

let cur = window.document.location.href
let pathname = ':'
let pos = cur.lastIndexOf(pathname)
let url = cur.substring(0, pos)
const baseUrl = `${url}:8083`

// const baseUrl = 'http://36.155.71.34:8080'
// const baseUrl = 'http://10.102.16.11:8183' // 最新ip请求地址
// const baseUrl = 'http://192.168.1.27:8282' // 27测试
// const baseUrl = 'http://localhost:8282'
// 创建axios实例
const httpService = axios.create({
  baseURL: baseUrl,
  // 请求超时时间
  timeout: 600000
})

// request拦截器
httpService.interceptors.request.use(config => {
  if (store.getters.token) {
    // 让每个请求携带自定义token 请根据实际情况自行修改
    config.headers['access_token'] = store.getters.token
  }
  config.headers['content-type'] = 'application/json; charset=utf-8'
  return config
}, error => {
  return Promise.reject(error)
})

// response拦截器
httpService.interceptors.response.use(
  response => {
    // code为非200是抛错 可结合自己业务进行修改
    const res = response.data
    let resString = (typeof (res.resCode) === 'undefined') || (res.resCode === null)
    if (resString === true) {
      return response
    } else {
      if (res.resCode !== '200' && res.resCode !== '11001') {
        Message({
          showClose: true,
          message: res.message,
          type: 'error',
          duration: 5 * 1000,
          onClose: function () {
            if (res.resCode === 'YST802' || res.resCode === 'YST803' || res.resCode === 'YST804' || res.resCode === 'YST805') {
              removeToken()
              router.go(0)
            }
          }
        })
        return Promise.reject('error')
      } else {
        return response.data
      }
    }
  },
  error => {
    Message({
      showClose: true,
      message: '服务器返回出错，请联系管理员！',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default httpService

export function baseInfo () {
  return baseUrl
}
